#include <arduino/Arduino.h>


int diodePins[] = { 2,3,4,5,6,7,8,9,10 };

int period = 100;

void setup(void)
{
  Serial.begin(9600);

  for (int i = 0; i < sizeof(diodePins)/sizeof(int); ++i)
  {
    pinMode(diodePins[i], OUTPUT);
    digitalWrite(diodePins[i], LOW);
  }
}


void blink(int diodeIdx, int time)
{
  digitalWrite(diodePins[diodeIdx], HIGH);
  delay(time);
  digitalWrite(diodePins[diodeIdx], LOW);
  delay(time);
}


bool read_string_from_serial(String& periodStr)
{
  int val = Serial.read();

  while (val != -1)
  {
    if (char(val) == '\r' || char(val) == '\n')
      return true;

    periodStr += char(val);

    val = Serial.read();
  }

  return false;
}


int convert_char_to_int(char c)
{
  if (c >= '0' && c <= '9')
    return int(c) - 48;

  return -1;
}


int convert_string_to_int(String const& str)
{
  int result = 0;
  int power = 1;

  for (int i = str.length() - 1; i >= 0; --i)
  {
    int val = convert_char_to_int(str[i]);

    if (val != -1)
    {
      result += power * val;
      power *= 10;
    }
    else return -1;
  }

  return result;
}


void update_period(String& periodStr)
{
  if (read_string_from_serial(periodStr))
  {
    int val = convert_string_to_int(periodStr);

    if (val != -1)
    {
      Serial.println(
            "Period updated to " +
            periodStr +
            " milliseconds.");

      period = val;
    }
    else
    {
      Serial.println(
            "Input is not a valid integer: \"" +
            periodStr +
            "\" -> error.");
    }

    periodStr = "";
  }
}


void loop(String& periodStr)
{
  for (int i = 0; i < sizeof(diodePins)/sizeof(int); ++i)
  {
    update_period(periodStr);
    blink(i, period);
  }
}

int main(void)
{
  init();

#if defined(USBCON)
  USBDevice.attach();
#endif

  setup();

  String period_str;

  while (true)
  {
    loop(period_str);
    if (serialEventRun) serialEventRun();
  }

  return 0;
}
